<?php

class epaywxh5Payment extends BasePayment {


    function get_payform($order_info) {
        $order_info=$this->get_order_info($order_info);
        
        if(!$order_info){
            return false;
        }
        $nonce_str=make_code(32);
        $values=array(
            'appid'=>Conf::get('payment_wx_appid'),
            'mch_id'=>Conf::get('payment_wx_mch_id'),
            'nonce_str'=>$nonce_str,
            'body'=>"微信H5支付",
            'out_trade_no'=>$order_info['order_sn'],
            'total_fee'=>intval(bcmul($order_info['money'],100 ,0)),
            'spbill_create_ip'=>real_ip(),
            'notify_url'=>site_url(). "/notifywx.php",
            'trade_type'=>'MWEB',
        );
    	$sign=$this->MakeSign($values);
        $values['sign']=$sign;
    	$xml = "<xml>";
    	foreach ($values as $key=>$val)
    	{
    		if (is_numeric($val)){
    			$xml.="<".$key.">".$val."</".$key.">";
    		}else{
    			$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    		}
        }
        $xml.="</xml>";
        $res=request_post('https://api.mch.weixin.qq.com/pay/unifiedorder',$xml);
        $res = json_decode(json_encode(simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        if($res['return_code']=='SUCCESS'){
            header('Location:'.$res['mweb_url'].'&redirect_url='.urlencode(site_url() . "/index.php?app=account_log&act=logall"));exit;
        }else{
            throw new Exception($res['return_msg']);
        }
        
    }
	public function MakeSign($values)
	{
		//签名步骤一：按字典序排序参数
		ksort($values);
		$string = $this->ToUrlParams($values);
		//签名步骤二：在string后加入KEY
		$string = $string . "&key=".Conf::get('payment_wx_key');
		//签名步骤三：MD5加密
		$string = md5($string);
		//签名步骤四：所有字符转为大写
		$result = strtoupper($string);
		return $result;
	}
	public function ToUrlParams($values)
	{
		$buff = "";
		foreach ($values as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}
}
?>
